package ksv.cron.controller;

import api.common.IdKey;
import api.common.result.Result;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import ksv.cron.CronConfig;
import ksv.cron.bean.SysCron;
import ksv.cron.bean.SysCronLog;
import ksv.cron.service.CronService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ServerWebExchange;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @创建人 xiaojiancheng
 * @时间 2020/8/16
 * @描述
 */
@RestController
@RequestMapping("/cron")
@Slf4j
@Api
public class CronController{
    @Resource
    private CronService cronService;

    @Resource
    private CronConfig cronConfig;

    @Resource
    IdKey idKey;

    @PostMapping(value="/list")
    @ApiOperation(value = "定时任务列表",tags="定时任务")
    public Result list(@RequestParam("size") Integer size,
                     @RequestParam("page") Integer page,
                     @RequestBody SysCron cron){

        List<SysCron> sysCrons = cronService.loadMoreCron(cron, new Page(page,size));
        return new Result().data(sysCrons);
    }


    @PostMapping("/save")
    @ApiOperation(value = "保存",tags="定时任务")
    public Result save(@RequestBody SysCron cron){
        cron.setId(idKey.longId());
        //  重新生成hash
        cron.setHash((int) (cron.getId() % cronConfig.getHashCapacity()));
        cronService.saveCron(cron);
        return new Result().data(cron);
    }

    //  通过携带的id去删除数据
    @PostMapping("saveAndDelete")
    @ApiOperation(value = "插入删除",tags="定时任务")
    public Result saveAndDelete(@RequestBody SysCron cron){
        cronService.saveAndDeleteCron(cron);
        return new Result().data(cron);
    }


    @PostMapping("/delete")
    @ApiOperation(value = "删除",tags="定时任务")
    public Result delete(@RequestBody SysCron cron){
        cronService.deleteCron(cron);
        return new Result().data(cron);
    }

    @PostMapping("/logs")
    @ApiOperation(value = "运行日志",tags="定时任务")
    public Result logs(@RequestBody SysCron cron){
        List<SysCronLog> logs = cronService.logs(cron);
        cron.setLogList(logs);
        return new Result().data(cron);
    }

    //  输出的测试 回调测试样例
    @PostMapping("/testCallback")
    @ApiOperation(value = "测试的回调地址",tags="定时任务")
    public Result testCallback(@RequestBody Map<String,Object> data){
        log.info("CronController testCallback data = {}",JSON.toJSONString(data));
        return new Result();
    }


    //  立刻执行一次
    @PostMapping("/executeOnce")
    @ApiOperation(value = "立刻执行一次",tags="定时任务")
    public Result executeOnce(@RequestBody SysCron cron){
        cronService.executeOnce(cron);
        return new Result();
    }
}
